package com.spider.demo4tcp1;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo2 {
    public static void main(String[] args) throws Exception {
        System.out.println("服务端启动了...");
        //目标：实现TCP通信下一发一收：服务端开发。
        //1.创建一个服务器Socket对象，绑定监听端口
        ServerSocket ss = new ServerSocket(8080);
        //2.调用accept方法，阻塞等待客户端连接，一旦有客户端连接就会返回一个Socket对象
        Socket socket = ss.accept();
        //3.获取输入流，读取数据
        InputStream is = socket.getInputStream();
        //4.把字节输入流转换成特殊数据输入流
        DataInputStream dis = new DataInputStream(is);
        //5.读取数据
        int id = dis.readInt();
        String msg = dis.readUTF();
        System.out.println("id:"+id+" 收到的客户端消息msg="+msg);
        //6.客户端的ip和端口
        System.out.println("客户端的ip:"+socket.getInetAddress().getHostAddress());
        System.out.println("客户端的端口:"+socket.getPort());
    }
}
